package com.crx.springbootinit.controller.user;


import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.crx.springbootinit.annotation.LogApiAnno;
import com.crx.springbootinit.annotation.LogLoginAnno;
import com.crx.springbootinit.common.BaseResponse;
import com.crx.springbootinit.common.ResultUtils;
import com.crx.springbootinit.model.dto.page.PageVO;
import com.crx.springbootinit.model.dto.post.PostOtherPageDTO;
import com.crx.springbootinit.model.dto.user.UserEnableDTO;
import com.crx.springbootinit.model.dto.user.UserLoginRequest;
import com.crx.springbootinit.model.dto.user.UserPageDTO;
import com.crx.springbootinit.model.dto.user.UserUpdateMyRequest;
import com.crx.springbootinit.model.entity.User;
import com.crx.springbootinit.model.vo.post.PostHomeVO;
import com.crx.springbootinit.model.vo.post.PostListVO;
import com.crx.springbootinit.model.vo.user.UserAndPostInfo;
import com.crx.springbootinit.model.vo.user.UserOtherAndPostInfo;
import com.crx.springbootinit.model.vo.user.UserPageVO;
import com.crx.springbootinit.service.IFollowService;
import com.crx.springbootinit.service.IUserService;
import com.crx.springbootinit.utils.JwtHelper;
import com.crx.springbootinit.utils.ThreadLocalUtil;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.util.DigestUtils;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * <p>
 * 用户表 前端控制器
 * </p>
 *
 * @author author
 * @since 2024-10-21
 */
@RestController
@RequestMapping("/user/user")
@Api(tags = "用户模块接口")
public class UserController {

    @Autowired
    private IUserService userService;
    @Autowired
    private IFollowService followService;
    @Autowired
    private RedisTemplate redisTemplate;

    @ApiOperation(value = "用户注册")
    @PostMapping("/register")
    public BaseResponse register(@RequestBody UserLoginRequest userLoginRequest) {
        if (StringUtils.isBlank(userLoginRequest.getUsername()) || StringUtils.isBlank(userLoginRequest.getPassword())) {
            return BaseResponse.error("账号或密码为空");
        }

        LambdaQueryWrapper<User> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(User::getAccount,userLoginRequest.getUsername());
        User user = userService.getOne(queryWrapper);
        if (user != null) {
            return BaseResponse.error("该账号已存在");
        }
        userService.register(userLoginRequest.getUsername(),userLoginRequest.getPassword());
        return BaseResponse.success();
    }

    @ApiOperation(value = "账号密码登录")
    @PostMapping("/loginByPassword")
    @LogLoginAnno(title = "登录", businessType = "POST")
    public BaseResponse loginByPassword(@RequestBody UserLoginRequest userLoginRequest) {
        if (StringUtils.isBlank(userLoginRequest.getUsername()) || StringUtils.isBlank(userLoginRequest.getPassword())) {
            return BaseResponse.error("账号或密码为空");
        }

        LambdaQueryWrapper<User> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(User::getAccount,userLoginRequest.getUsername());
        User user = userService.getOne(queryWrapper);
        if (user == null) {
            return BaseResponse.error("不存在该账号");
        }
        if (!user.getPassword().equals(DigestUtils.md5DigestAsHex(userLoginRequest.getPassword().getBytes()))) {
            return BaseResponse.error("输入密码错误");
        }
        if (user.getRoleStatus().equals(0)) {
            return BaseResponse.error("该账号被禁用");
        }

        //生成token,存入redis且返回
        String token = JwtHelper.createToken(user.getId(), user.getAccount(), user.getUserRole());
        redisTemplate.opsForValue().set(token,user.getId());

        return BaseResponse.success(token);
    }

    @ApiOperation(value = "获取当前用户信息")
    @GetMapping("/getMyUserInfo")
    @LogApiAnno(title = "用户模块", businessType = "GET")
    public BaseResponse getMyUserInfo(@RequestParam(defaultValue = "1") int pageNum, @RequestParam(defaultValue = "10") int pageSize) {
        Long userId = ThreadLocalUtil.get("userId");
        UserAndPostInfo userAndPostInfo = userService.getUserAndPostInfo(userId,pageNum,pageSize);
        return BaseResponse.success(userAndPostInfo);
    }

    @ApiOperation(value = "获取用户发布列表")
    @GetMapping("/getMyPost")
    @LogApiAnno(title = "用户模块", businessType = "GET")
    public BaseResponse getMyPost(@RequestParam(defaultValue = "1") int pageNum, @RequestParam(defaultValue = "10") int pageSize, @RequestParam int type) {
        Long userId = ThreadLocalUtil.get("userId");
        PageVO<PostHomeVO> postHomeVOPageVO = userService.getMyPost(userId,pageNum,pageSize,type);
        return BaseResponse.success(postHomeVOPageVO);
    }
    /**
     * 获取别人用户信息
     * @return
     */
    @GetMapping("/getOtherUserInfo")
    @ApiOperation("获取别人用户信息")
    @LogApiAnno(title = "用户模块", businessType = "GET")
    public BaseResponse<UserOtherAndPostInfo> listOtherPosts(Long userId) {
        UserOtherAndPostInfo userOtherAndPostInfo = new UserOtherAndPostInfo();
        UserAndPostInfo userAndPostInfo = userService.getUserAndPostInfo(userId,1,10);
        Long myUserId = ThreadLocalUtil.get("userId");
        Boolean isFollow = followService.isFollow(myUserId,userId);
        userOtherAndPostInfo.setUserAndPostInfo(userAndPostInfo);
        userOtherAndPostInfo.setIsFollow(isFollow);
        return ResultUtils.success(userOtherAndPostInfo);
    }

    @ApiOperation(value = "获取别人发布列表")
    @GetMapping("/getOtherPost")
    @LogApiAnno(title = "用户模块", businessType = "GET")
    public BaseResponse getOtherPost(PostOtherPageDTO postOtherPageDTO) {
        PageVO<PostHomeVO> postHomeVOPageVO = userService.getMyPost(postOtherPageDTO.getUserId(),postOtherPageDTO.getPageNo(),postOtherPageDTO.getPageSize(),0);
        return BaseResponse.success(postHomeVOPageVO);
    }

    @ApiOperation(value = "获取当前用户信息")
    @GetMapping("/getDirctUserInfo")
    @LogApiAnno(title = "用户模块", businessType = "GET")
    public BaseResponse getDirctUserInfo(HttpServletRequest request) {
        String token = request.getHeader("token");
        Long userId = JwtHelper.getUserId(token);

        Map map=new HashMap<>();
        LambdaQueryWrapper<User> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(User::getId,userId);
        User user = userService.getOne(queryWrapper);
        map.put("avatar",user.getAvatar());
        map.put("nickname",user.getNickname());
        map.put("address",user.getAddress());
        map.put("gender",user.getGender());
        map.put("bio",user.getBio());
        map.put("birthdate",user.getBirthDate());

        return BaseResponse.success(map);
    }

    @ApiOperation(value = "根据token获取用户")
    @GetMapping("/getUserByToken")
    @LogApiAnno(title = "用户模块", businessType = "GET")
    public BaseResponse getUserByToken(String token) {
        Long userId = JwtHelper.getUserId(token);
        User user = userService.getById(userId);
        return BaseResponse.success(user);
    }

    @ApiOperation(value = "退出登录")
    @PostMapping ("/logout")
    @LogApiAnno(title = "用户模块", businessType = "POST")
    public BaseResponse logout(@RequestHeader String token) {
        Boolean delete = redisTemplate.delete(token);
        return BaseResponse.success();
    }

    @ApiOperation(value = "编辑个人资料")
    @PostMapping ("/editPrivateMessage")
    @LogApiAnno(title = "用户模块", businessType = "GET")
    public BaseResponse editPrivateMessage(@RequestBody UserUpdateMyRequest userUpdateMyRequest) {
        userService.editPrivateMessage(userUpdateMyRequest);
        return BaseResponse.success();
    }

}
